<template>
  <el-tooltip content="搜索文章">
    <!-- 搜索文章 -->
    <KoiSvgIcon
      name="koi-menu-search"
      width="30"
      height="30"
      class="p-5px outline-none bg-[rgba(50,50,50,0.06)] dark:bg-[rgba(0,0,0,0.1)] rounded-full"
      @click="handleOpenDialog"
    ></KoiSvgIcon>
  </el-tooltip>

  <KoiDialog ref="koiDialogRef" :title="title" :footerHidden="true" top="6vh" :width="466" :height="636">
    <template #content>
      <!-- 搜索框 Begin -->
      <div class="flex flex-justify-center">
        <div
          class="search-middle w-100% p-8px bg-[rgba(255,255,255,0.6)] dark:bg-#434343 rounded-10px border-1px border-solid border-[--el-color-primary] flex flex-items-center"
        >
          <input
            v-model="searchParams.articleTitle"
            type="text"
            placeholder="请输入文章标题"
            class="w-100% h-26px bg-transparent border-0 text-14px outline-0 font-500 text-#303133 dark:text-#E5EAF3"
            @input="handleSearch"
          />
          <el-icon 
            :size="26" 
            class="p-b-1px m-r-4px outline-none text-[--el-color-primary-light-5] dark:text-#E5EAF3" 
          >
            <Search/>
          </el-icon>
        </div>
      </div>
      <!-- 搜索框 End -->

      <!-- 搜索结果 Begin -->
      <div class="flex flex-justify-center m-b-26px">
        <div
          class="overflow-y-auto w-100% h-518px m-t-8px rounded-10px border-1px border-solid border-[--el-color-primary-light-5] bg-#FFF dark:bg-#1A1A1A p-6px"
        >
          <div class="flex flex-items-center">
            <div
              class="m-t-2px m-b-4px flex flex-items-center flex-justify-center text-16px text-[--el-color-primary] max-w-180px rounded-6px border-2px border-dashed border-[--el-color-primary-light-2] hover:border-[--el-color-primary] hover:bg-[--el-color-primary-light-7] bg-[--el-color-primary-light-8] backdrop-blur-3xl p-l-14px p-r-18px p-y-2px transition-all duration-600 transition-ease-in-out"
            >
              <KoiSvgIcon name="koi-menu-search" width="22" height="22" class="p-b-3px m-r-5px outline-none"></KoiSvgIcon>
              <div class="font-bold tracking-2px line-clamp-1">搜索结果[{{ total }}]</div>
            </div>
          </div>
          <div
            class="border-1px border-solid border-[--el-border-color] hover:border-[--el-color-primary] rounded-10px p-x-6px p-t-8px p-b-2px flex m-t-5px transition-all duration-600 transition-ease-in-out"
            v-if="!searchIsSkeleton"
            v-for="item in searchList"
            :key="item.articleId"
          >
            <div class="pos-relative">
              <el-image :src="item.picture" fit="cover" class="w-110px h-72px rounded-4px"></el-image>
              <div class="pos-absolute left-0 top-0">
                <div class="text-#FAFAFA text-8px whitespace-nowrap bg-[rgba(0,0,0,0.3)] p-x-6px p-y-4px rounded-4px max-w-52px overflow-hidden relative">
                  <div class="max-w-full overflow-hidden text-ellipsis">
                    {{ item.categoryName }}
                  </div>
                </div>
              </div>
            </div>
            <div class="flex flex-col flex-justify-center m-l-10px m-t--4px">
              <div
                class="text-14px m-b-4px text-#333 dark:text-#D8D8D8 font-500 hover:text-#6E6E6E dark:hover:text-#FFF line-clamp-2 gradient-title h-40px"
              > 
                <div v-html="item.highlightArticleTitle" @click="handleArticleContent(item.articleId)"></div>
                <!-- {{ item.articleTitle }} -->
              </div>
              <div class="text-12px text-#7E7E7E dark:text-#D8D8D8">{{ item.createTime }}</div>
            </div>
          </div>
          <!-- 骨架屏 Begin -->
          <div class="m-t-16px" v-else>
            <el-skeleton animated>
              <template #template>
                <div class="w-100% flex flex-justify-between m-b-15px" v-for="(_item, index) in 10" :key="index">
                  <el-skeleton-item variant="image" class="rounded-6px w-100px h-100px m-r-10px" />
                  <el-skeleton-item class="flex-1 h-100px" />
                </div>        
              </template>
            </el-skeleton>  
          </div>
          <!-- 骨架屏 End --> 
          <!-- 加载更多 -->
          <div class="flex flex-justify-center m-t-16px" v-if="total > 10">
            <el-button
              type="primary"
              text
              bg
              :loading="loading"
              :disabled="searchParams.pageNo >= pages"
              v-debounce="handleMore"
            >
              {{ loadingText }}
            </el-button>
          </div>
          <div class="flex flex-justify-center" v-if="searchList.length == 0 && !searchIsSkeleton">
            <el-empty :image="errorUrl" :image-size="300" description="主人，没有数据了哟👻"></el-empty>
          </div>
        </div>
      </div>
      <!-- 搜索结果 End -->

      <!-- 底部 Begin -->
      <div class="flex flex-justify-center">
        <div class="text-15px text-#6E6E6E">基于 Elasticsearch  全文检索引擎开发</div>
      </div>
      <!-- 底部 End -->
    </template>
  </KoiDialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { koiMsgWarning, koiMsgError } from "@/utils/koi.ts";
import { listSearch } from "@/api/blog/article/index.ts"; 
import { useDebounceFn } from '@vueuse/core';
import errorUrl from "@/assets/images/error/404.png";

const koiDialogRef = ref();
const title = ref("全局搜索");

/** 查询参数 */
const searchParams = ref<any>({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  articleTitle: "" // 文章标题
});

const searchList = ref<any>([]);
// 总条数
const total = ref(0);
// 总页数
const pages = ref(0);
// 骨架屏是否显示[默认关闭]
const searchIsSkeleton = ref(false);

/** 打开对话框 */
const handleOpenDialog = () => {
  koiDialogRef.value.koiOpen();
  searchParams.value.pageNo = 1;
  searchParams.value.articleTitle = "";
  searchList.value = [];
  total.value = 0;
};

/** 全局搜索 */
const handleSearch = useDebounceFn(async () => {
  try {
    searchIsSkeleton.value = true;
    searchParams.value.pageNo = 1;
    searchList.value = [];
    const res: any = await listSearch(searchParams.value);
    searchList.value = res.data.records;;
    total.value = res.data.total;
    pages.value = res.data.pages;
    if (searchList.value.length > 0) {
      searchList.value = res.data.records.map((item: any) => ({
        ...item,
        highlightArticleTitle: highlightText(item.articleTitle, searchParams.value.articleTitle),
      }));
    }
    loadingText.value = "加载更多...";
    searchIsSkeleton.value = false;
  } catch (error) {
    console.log(error);
    koiMsgError("数据查询失败，请刷新重试🌻");
  }
}, 500);

/** 高亮文本 */
const highlightText = (text: any, keyword: any) => {
  if (!text || !keyword) return text;

  // 转义特殊字符
  const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

  // 创建正则表达式，忽略大小写
  const regex = new RegExp(`(${escapedKeyword})`, 'gi');

  // 使用 font 标签包裹关键词
  return text.replace(regex, '<font style="color: var(--el-color-primary) !important;">' + keyword + '</font>');
};

onMounted(() => {
  searchParams.value.pageNo = 1;
  searchList.value = [];
});

const loading = ref(false);
const loadingText = ref("加载更多...");

/** 全局搜索 + 加载更多 */
const handleMoreSearch = async () => {
  try {
    searchIsSkeleton.value = true;
    const res: any = await listSearch(searchParams.value);
    searchList.value = searchList.value.concat(res.data.records);;
    total.value = res.data.total;
    pages.value = res.data.pages;
    if (searchList.value.length > 0) {
      searchList.value = res.data.records.map((item: any) => ({
        ...item,
        highlightArticleTitle: highlightText(item.articleTitle, searchParams.value.articleTitle),
      }));
    }
    searchIsSkeleton.value = false;
  } catch (error) {
    console.log(error);
    koiMsgError("数据查询失败，请刷新重试🌻");
  }
};

/** 加载更多 */
const handleMore = useDebounceFn(async () => {
  loadingText.value = "加载中...";
  loading.value = true;
  searchParams.value.pageNo++;
  if (searchParams.value.pageNo > pages.value) {
    loadingText.value = "亲，我也是有底线的！";
    loading.value = false;
    return;
  }
  await handleMoreSearch();
  if (searchParams.value.pageNo == pages.value) {
    loadingText.value = "亲，我也是有底线的！";
    loading.value = false;
    return;
  }
  loadingText.value = "加载更多...";
  loading.value = false;
}, 500);

/** 文章内容 */
const handleArticleContent = (articleId: any) => {
  if (articleId) {
    window.open(`/article/content/${articleId}`, "_blank");
  } else {
    koiMsgWarning("未获取文章参数，请刷新页面重试");
  }
};
</script>

<style lang="scss" scoped>
/** 搜索框样式 */
.search-middle input::placeholder {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-color-primary-light-3);
}
</style>
